package top.ahzy.seobench.sparkLite;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.ahzy.seobench.sparkLite.model.RoleContent;
import top.ahzy.seobench.sparkLite.model.SparkModel;
import top.ahzy.seobench.websocket.MessageSocket;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Service
public class SparkService {
    public static final Map<String, SparkModel> sparkWebSocketMap = new HashMap<>();

    @Autowired
    private MessageSocket messageSocket;

    public void send(String token, String context)  {

        JSONObject requestJson = new JSONObject();
        JSONObject header = new JSONObject();  // header参数
        header.set("app_id", SparkConst.appid);
        header.set("uid",UUID.randomUUID().toString().substring(0, 10) );

        JSONObject parameter = new JSONObject(); // parameter参数
        JSONObject chat = new JSONObject();
        chat.set("domain", SparkConst.domain);
        chat.set("temperature", 0.5);
        chat.set("max_tokens", 4096);
        parameter.set("chat", chat);

        JSONObject payload = new JSONObject(); // payload参数
        JSONObject message = new JSONObject();
        JSONArray text = new JSONArray();

        // 历史问题获取
        if (sparkWebSocketMap.containsKey(token) && CollUtil.isNotEmpty(sparkWebSocketMap.get(token).getHistoryList())) {
            for (RoleContent tempRoleContent : sparkWebSocketMap.get(token).getHistoryList()) {
                text.add(JSON.toJSON(tempRoleContent));
            }
        }

        // 最新问题
        RoleContent roleContent = new RoleContent();
        roleContent.setRole("user");
        roleContent.setContent(context);
        text.add(JSON.toJSON(roleContent));


        message.set("text", text);
        payload.set("message", message);
        requestJson.set("header", header);
        requestJson.set("parameter", parameter);
        requestJson.set("payload", payload);

        try {
            if(sparkWebSocketMap.containsKey(token)){
                sparkWebSocketMap.get(token).getSparkWebSocket().send(sparkWebSocketMap.get(token),requestJson.toString());
            }else {
                SparkWebSocket sparkWebSocket = new SparkWebSocket(messageSocket);
                SparkModel sparkModel = new SparkModel();
                sparkModel.setSparkWebSocket(sparkWebSocket);
                sparkWebSocket.setToken(token);
                sparkWebSocketMap.put(token,sparkModel);
                sparkWebSocket.send(sparkWebSocketMap.get(token),requestJson.toString());
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
